package main

import (
	"bytes"
	"fmt"
	"strconv"
)

func main() {
	x := -123
	fmt.Println(reverse(x))
}

func reverse(x int) int {
	var buffer bytes.Buffer

	xStr := strconv.Itoa(x)

	if x < 0 {
		buffer.WriteString("-")
		xStr = reverseString(xStr[1:])
	} else {
		xStr = reverseString(xStr)
	}

	buffer.WriteString(xStr)

	result := buffer.String()

	i64, err := strconv.ParseInt(result, 10, 64)
	if err != nil {
		return 0
	}

	if i64 > 2147483647 || i64 < -2147483648 {
		return 0
	}
	return int(i64)

}

func reverseString(s string) string {
	runes := []rune(s)
	for from, to := 0, len(runes)-1; from < to; from, to = from+1, to-1 {
		runes[from], runes[to] = runes[to], runes[from]
	}
	return string(runes)
}
